package cn.liuweiwei.controller;


import cn.liuweiwei.domain.Message;
import cn.liuweiwei.service.MessageService;
import cn.liuweiwei.util.MailUtils;
import cn.liuweiwei.util.RandomCharsUtils;
import cn.liuweiwei.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("messages")
@CrossOrigin
public class EmailController {

    @Autowired
    private MessageService messageService;

    @PostMapping("register/{code}")
    public Result registerEmail(@RequestBody Message message,
                                @PathVariable("code") String code, HttpSession session) {
        String codeMsg = (String) session.getAttribute("code");
        if (!code.equalsIgnoreCase(codeMsg)) {
            return Result.error("验证码不正确！！");
        }
        messageService.insertOneMessage(message);
        return Result.success("验证成功");
    }

    @PostMapping("email/{email}")
    public Result sendEmailCode(@PathVariable("email") String email, HttpSession session) throws Exception {
        String code = RandomCharsUtils.RandomChars(5);
        MailUtils.sendMail(email, "你的邮箱验证码是：" + code);
        session.setAttribute("code", code);
        return Result.success("验证码发送成功");
    }
}
